<!-- 商品管理 -->
<template>
    <div class="product-admin">
        <h3>商品列表</h3>
        <el-card>
            <div slot="header" class="clearfix header-bar">
                <div class="left">
                    <span @click="handleOut" :class="{ active: status === 1 }">出售中的商品</span>
                    <span @click="handleNew" :class="{ active: newProduct === 1 }">新品</span>
                    <span @click="handleOff" :class="{ active: status === 0 }">已下架商品</span>
                </div>
                <!-- <div class="right">
                    <el-button type="primary" @click="handleAdd">添加商品</el-button>
                </div> -->
            </div>

            <el-form>
                <div class="select-bar">
                    <el-row :gutter="5">
                        <el-col :span="7">
                            <el-form-item label="商品名称">
                                <el-input v-model="search" placeholder="输入商品名称" clearable class="search-input"
                                    @keyup.enter.native="handleSearch" size="medium" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="分类">
                                <el-cascader v-model="categoryId" :options="cascader" :props="{ checkStrictly: true }"
                                    @change="CasChange" placeholder="请选择分类" size="medium" clearable></el-cascader>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item>
                                <el-button type="primary" v-click-blur @click="handleSearch" size="medium"
                                    plain>搜索</el-button>
                                <el-button @click="reset" size="medium" v-click-blur plain>重置</el-button>

                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item>
                            <el-button type="primary" size="medium" v-click-blur @click="handleAdd">添加商品</el-button>
                            <el-button size="medium" v-click-blur @click="handleBatchBan"
                                :disabled="selectedProducts.length == 0" v-if="!newProduct">批量{{ status == 1 ? '下架' :
                                '上架' }}商品</el-button>
                        </el-form-item>
                    </el-row>


                </div>
            </el-form>


            <el-table :data="products" :header-cell-style="{ background: '#F5F6FA', color: '#000' }" style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column label="图片" width="120">
                    <template slot-scope="scope">
                        <el-image v-if="scope.row.mainImage" style="width: 80px; height: 80px;"
                            :src="$getImgUrl(scope.row.mainImage.split(',')[0])" fit="cover" />
                        <span v-else>暂无图片</span>
                    </template>
                </el-table-column>
                <el-table-column prop="productName" label="商品名称" min-width="160" />
                <el-table-column prop="price" label="上架状态" width="100">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.status" @change="handleStatusChange(scope.row)"></el-switch>
                    </template>
                </el-table-column>


                <el-table-column prop="categoryName" label="分类" min-width="120" />
                <el-table-column prop="price" label="价格" width="100">
                    <template slot-scope="scope">
                        <span v-if="scope.row.defaultPrice != null">¥{{ scope.row.defaultPrice }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" v-click-blur @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="mini" v-click-blur type="danger"
                            @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="footer" v-if="page.total > 0">
                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="page.pageNum" :page-sizes="[5, 10, 20, 50]" :page-size="page.pageSize"
                    layout="total, sizes, prev, pager, next" :total="page.total" class="pagination" />
            </div>
        </el-card>
        <DrawerView ref="drawerRef" :title="drawerTitle" :visible.sync="drawer" :product="currentProduct"
            @saved="handleSaved" />
    </div>
</template>

<script>
import { getProducts, removeProduct, getProductById, productBan, productBatchBan } from '@/apis/product'
import { mapState } from 'vuex'
import DrawerView from './DrawerView.vue'
export default {
    components: { DrawerView },
    name: 'ProductAdmin',
    data() {
        return {
            products: [],
            search: '',
            categoryId: null,
            newProduct: null,
            status: 1,
            drawer: false,
            drawerTitle: '',
            currentProduct: null,
            page: {
                pageNum: 1,
                pageSize: 5,
                total: 0
            },
            selectedProducts: []
        }
    },
    computed: {
        ...mapState('category', ['cascader']),
    },
    created() {
        this.getProductList()
    },
    methods: {
        //处理表格选中
        handleSelectionChange(selection) {
            this.selectedProducts = selection.map(item => {
                return item.productId
            })
        },
        //批量设置商品上下架
        handleBatchBan() {
            let newStatus = 0
            if (this.status == 1) {
                newStatus = 0
            } else {
                newStatus = 1
            }
            this.$confirm(`确认下架选中的 ${this.selectedProducts.length} 条商品吗?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                productBatchBan(newStatus, this.selectedProducts).then(() => { this.getProductList })
            }).catch(() => {
                // 用户点了取消或关闭确认框，不做任何处理
            })


        },
        //处理新品
        handleNew() {
            this.newProduct = 1
            this.status = null
            this.getProductList()
        },
        //处理在售
        handleOut() {
            this.status = 1
            this.newProduct = null
            this.getProductList()
        },
        //处理下架
        handleOff() {
            this.status = 0
            this.newProduct = null
            console.log(this.status)
            this.getProductList()
        },
        //重置
        reset() {
            this.categoryId = null,
                this.search = '',
                this.getProductList()
        },
        //获取商品列表
        async getProductList() {

            const params = {
                pageNum: this.page.pageNum,
                pageSize: this.page.pageSize,
                categoryId: this.categoryId || null,
                search: this.search || null,
                newProduct: this.newProduct,
                status: this.status
            }
            const res = await getProducts(params)
            if (res && res.data) {
                // 兼容后端分页结构：data.records + data.total
                this.products = res.data.records || res.data
                // 将status从0/1转换为boolean类型
                this.products = this.products.map(item => ({
                    ...item,
                    status: item.status === 1
                }))
                this.page.total = res.data.total || (Array.isArray(this.products) ? this.products.length : 0)
            }

        },

        //级联选择器change事件
        CasChange() {
            if (Array.isArray(this.categoryId) && this.categoryId.length > 0) {
                this.categoryId = this.categoryId[this.categoryId.length - 1]
            }
            console.log(this.categoryId)
            this.getProductList()
        },

        //处理分页大小变化事件
        handleSizeChange(size) {
            this.page.pageSize = size
            this.page.pageNum = 1
            this.getProductList()
        },

        //处理当前页码变化事件
        handleCurrentChange(page) {
            this.page.pageNum = page
            this.getProductList()
        },

        //搜索
        handleSearch() {
            this.page.pageNum = 1
            this.getProductList()
        },
        // 添加商品
        handleAdd() {
            this.currentProduct = null
            this.drawerTitle = '添加商品'
            this.drawer = true
        },
        // 编辑商品
        async handleEdit(row) {
            const res = await getProductById(row.productId)
            this.drawerTitle = '编辑商品'
            this.currentProduct = res.data
            this.drawer = true
        },
        // 删除商品
        handleDelete(row) {
            this.$confirm('确认删除该商品吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeProduct(row.productId).then(() => {
                    this.getProductList()
                })
            }).catch(() => {
                // 用户点了取消或关闭确认框，不做任何处理，避免控制台报错
            })
        },
        // 抽屉保存后回调
        handleSaved() {
            this.drawer = false
            this.getProductList()
        },
        // 处理上架状态变更
        async handleStatusChange(row) {
            // 如果需要同步到后端，可以在这里调用API
            // 将boolean转换回0/1发送给后端
            const statusValue = row.status ? 1 : 0
            // console.log(`商品 ${row.productId} 状态变更为: ${statusValue}`)
            const params = {
                productId: row.productId,
                status: statusValue
            }
            const res = await productBan(params)
            if (res.status == "success") {
                setTimeout(this.getProductList, 500)

            }
            // 示例: await updateProductStatus(row.productId, statusValue)
        },

    }
}
</script>

<style lang='less' scoped>
.left {
    display: flex;
    gap: 10px;

    span {
        padding: 5px 8px;
        border: 1px solid white;
        text-align: center;
        font-size: 14px;
        cursor: pointer;
    }

    span.active {
        background-color: #EFF2FE;
        border: 1px solid #2955E7;
        border-radius: 4px;
        color: #2955E7;
    }
}

.product-admin {
    padding: 20px;
}

.header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-input {
    width: 220px;
    margin-right: 10px;
}

.footer {
    margin-top: 16px;
    text-align: right;
}

/**解决el-button的:focus引起的样式问题*/
.el-button.is-link:not(.is-disabled):focus,
.el-button.is-link:not(.is-disabled):hover {
    color: var(--el-button-text-color);
}
</style>
